package com.my.storage.exception.handler;

import com.my.storage.exception.error.BusinessException;
import com.my.storage.interceptor.result.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 服务端全局的异常处理器
 *
 * @author hangwen
 */

@RestControllerAdvice
@ResponseBody
public class ServiceExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(ServiceExceptionHandler.class);

    @ExceptionHandler
    @ResponseBody
    public Result<Void> handleException(BusinessException ex) {
        return Result.error(ex.getErrorCode(), ex.getMessage());
    }

    /**
     * 处理意料之外的运行时异常，通常来说：就是bug......也可能是其他尚未被处理的运行时异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler
    @ResponseBody
    public ResponseEntity handleException(RuntimeException ex) {
        if (logger.isErrorEnabled()) {
            logger.error("ServiceExceptionHandler catch a unhandled runtime exception!", ex);
        }

        return ResponseEntity.status(500).body(Result.error("500", ex.getMessage()));
    }

}
